package com.myexam.dao.impl;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.HibernateCallback;
import org.springframework.orm.hibernate4.HibernateTemplate;
import org.springframework.stereotype.Repository;

import com.myexam.dao.TeacherDao;
import com.myexam.model.Exam;
import com.myexam.model.Score;
import com.myexam.model.Teacher;
import com.myexam.util.Page;
import com.myexam.util.PageUtil;
@Repository
public class TeacherDaoimpl implements TeacherDao {
	
	@Autowired
	private HibernateTemplate hibernateTemplate;
	
	@Override
	public Teacher findByTeacherID(String teacherID) {
		// TODO Auto-generated method stub
		return (Teacher) hibernateTemplate.get(Teacher.class, teacherID);
	}
	
	public void addExam(Exam exam) {
		this.hibernateTemplate.save(exam);
		
	};

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public List<Exam> findExamByPage(final Page page){
		List<Exam> exams = (List<Exam>)this.hibernateTemplate.execute(new HibernateCallback() {
			
			@Override
			public Object doInHibernate(Session session) throws HibernateException {
				// TODO Auto-generated method stub
				String hql = "from Exam exm";
				List<Exam> list = PageUtil.getList(session, hql,page);
				return list;
			}
		});
		return exams;
	}
	
	@SuppressWarnings("unchecked")
	public List<Exam> findExam(){
		return (List<Exam>) this.hibernateTemplate.find("from Exam exam where exam.exam_stage = 1");
	}
	
	@Override
	public Exam findExamByID(int examID) {
		// TODO Auto-generated method stub
		return (Exam) this.hibernateTemplate.get(Exam.class, examID);
	}
	public int findExamCount(){
		return this.hibernateTemplate.find("from Exam exm").size();
	}
	public void deleteExam(int exam_id) {
		this.hibernateTemplate.delete(this.hibernateTemplate.load(Exam.class, exam_id));
	};
	
	@Override
	public void updateExam(Exam exam) {
		// TODO Auto-generated method stub
		this.hibernateTemplate.update(exam);
	}
	public Exam examUpdateShow(int examID) {
		return (Exam) this.hibernateTemplate.get(Exam.class, examID);
	};
	
	@SuppressWarnings("unchecked")
	@Override
	public List<Score> findScoreByID(int studentID) {
		// TODO Auto-generated method stub
		return (List<Score>) this.hibernateTemplate.find("from Score ss where ss.studentID = ?",studentID);
	}
}
